import React, { PureComponent, Fragment } from 'react';
import {
  Row,
  Col,
  Icon,
  Card,
  Tabs,
  Table,
  Radio,
  DatePicker,
  Menu,
  Dropdown,
  Select,
  Button,
  Tooltip as AntTooltip
} from 'antd';
import DataSet from "@antv/data-set";
import styles from './index.less';
import {
  ChartCard,
  Field,
  Bar,
  MiniProgress,
} from 'components/Charts';
import GeneralTableComponent from 'components/GeneralTableComponent';
import {
  G2,
  Chart,
  Geom,
  Axis,
  Tooltip,
  Coord,
  Label,
  Legend,
  View,
  Guide,
  Shape,
  Facet,
  Util
} from "bizcharts";
import moment from 'moment';

const TabPane = Tabs.TabPane;
const { RangePicker } = DatePicker;

export default class BackStatisticsComponent extends PureComponent {
  // constructor(props) {
  //   super(props);
  //   this.state = {

  //   };
  // }

  componentDidMount() {

  }

  componentWillReceiveProps(nextProps) {

  }

  formatMapData = (mapData, xCoordinate, xkey) => {
    // 用于将map型数据 { a: { x1: '0', x2: '1', } b: { x1: '2', x2: '3', } }
    // 格式化成 [{ [xCoordinate]: 'x1', a: '0', b: '2' }, { [xCoordinate]: 'x2', a: '1', b: '3'}]
    let formatData = [];
    let pick = {
      maxLength: 0,
      maxName: '',
      keysArray: [],
    };
    //返回数组长度方法
    function _length(obj) {
      let _count = 0;
      for (let key of Object.keys(obj)) {
        _count++;
      }
      return _count;
    };
    //判断是否是数字或者undefined
    function _isNumber(val) {
      return typeof(val) === "number" || typeof(val) === "undefined"
    }
    //找到深度为1的内容最多的那条数据对象
    if (mapData) {
      for (let [key, val] of Object.entries(mapData)) {
        pick.keysArray.push(key);
        if (val && _length(val) > pick.maxLength) {
          [pick.maxLength, pick.maxName] = [_length(val), key];
        }
      }
    }
    //以最长的那条数据对象为基础初始化目标数组
    for (let [key, val] of Object.entries(mapData[pick.maxName])) {
      let _buf = {
        [xCoordinate]: key
      }
      pick.keysArray.forEach((val, index, arr) => {
        _buf[val] = ''
      })
      formatData.push(_buf);
    }
    //将所有的数据填充到初始化完毕的目标数组中
    formatData.forEach((_val, _index, _arr) => {
      pick.keysArray.forEach((val, index, arr) => {
        //这里对每一条数据进行处理
        //处理数据为 纯数字/字符串(带%) 的情况
        //处理数据为 undefined 的情况
        if (mapData[val] && !_isNumber(xkey ? mapData[val][_val[xCoordinate]][xkey] : mapData[val][_val[xCoordinate]])) {
          _val[val] = mapData[val] && mapData[val][_val[xCoordinate]] ? Number(mapData[val][_val[xCoordinate]][xkey].replace('%', '')) : 0;
          // _val[val] = Number(xkey ? mapData[val][_val[xCoordinate]][xkey] : mapData[val][_val[xCoordinate]]);
        } else {
          _val[val] = mapData[val] ? (typeof(xkey ? mapData[val][_val[xCoordinate]][xkey] : mapData[val][_val[xCoordinate]]) === "undefined" ? 0 : Number(xkey ? mapData[val][_val[xCoordinate]][xkey] : mapData[val][_val[xCoordinate]])) : 0;
        }
      })
    });
    return formatData
  };

  selectDataByAmount = (origin, time, type) => {
    const { allData : { repayTrendData } } = this.props;
    switch(type) {
      case '还款金额':
        return origin === '还款金额' ? (repayTrendData.repayRateMap[time].repayAmount) 
        : (origin === '近7天还款金额' ? (repayTrendData.last7DayAverageRepayRateMap[time].repayAmount) 
          : (origin === '近30天还款金额' ? repayTrendData.last30DayAverageRepayRateMap[time].repayAmount 
            : '') )
        break;
      case '还款率':
        return origin === '还款金额' ? (repayTrendData.repayRateMap[time].repayRate) 
        : (origin === '近7天还款金额' ? (repayTrendData.last7DayAverageRepayRateMap[time].repayRate) 
          : (origin === '近30天还款金额' ? repayTrendData.last30DayAverageRepayRateMap[time].repayRate 
            : '') )
        break;
      case '还款笔数':
        return origin === '还款金额' ? (repayTrendData.repayRateMap[time].repayNum) 
        : (origin === '近7天还款金额' ? (repayTrendData.last7DayAverageRepayRateMap[time].repayNum) 
          : (origin === '近30天还款金额' ? repayTrendData.last30DayAverageRepayRateMap[time].repayNum 
            : '') )
        break;
      default:
        return ''
        break;
    }
  };

  render() {
    const {
      userType,
      allData,
      loading,
      type,
      columnsAll,
      columns1,
      columns2,
      tableChange,
      userSelectFn,
      currentUser,
      datePickerFn,
      dateRanges,
    } = this.props;
    const {
      abData,
      nbData,
      obData,
      aoData,
      noData,
      ooData,
      repayTableData,
      overdueTableData,
      repayTrendData,
      overdueTrendData,
      totalRepayCountData,
      totalRepayTableData
    } = allData;

    let _dateRanges = [];
    Array.prototype.remove = function(from, to) {
      let rest = this.slice((to || from) + 1 || this.length);
      this.length = from < 0 ? this.length + from : from;
      return this.push.apply(this, rest);
    };

    if (repayTableData) {
      repayTableData.list.remove(0);
    }
    if (overdueTableData) {
      overdueTableData.list.remove(0);
    }
    if (totalRepayTableData) {
      totalRepayTableData.list.remove(0);
    }

    if (dateRanges && dateRanges[0]) {
      _dateRanges = [moment(dateRanges[0], "YYYY-MM-DD"), moment(dateRanges[1], "YYYY-MM-DD")];
    }

    const topColResponsiveProps = {
      xs: 24,
      sm: 24,
      md: 24,
      lg: 8,
      xl: 8,
    };

    const topColResponsiveProps_B = {
      xs: 24,
      sm: 24,
      md: 24,
      lg: 12,
      xl: 12,
    };

    //初始化trend数据
    let formatTrendData = [],
        _xFields = [];
    switch(type) {
      case 'all':
        if (repayTrendData) {
          let _repayTrendData = {
            '还款金额': repayTrendData.repayRateMap,
            '近7天还款金额': repayTrendData.last7DayAverageRepayRateMap,
            '近30天还款金额': repayTrendData.last30DayAverageRepayRateMap,
          }
          formatTrendData = this.formatMapData(_repayTrendData, 'time', 'repayRate');
          for (let [key, val] of Object.entries(_repayTrendData)) {
            if (val) {
              _xFields.push(key);
            }
          }
        }
        break;
      case 'back':
        if (repayTrendData) {
          let _repayTrendData = {
            '还款金额': repayTrendData.repayRateMap,
            '近7天还款金额': repayTrendData.last7DayAverageRepayRateMap,
            '近30天还款金额': repayTrendData.last30DayAverageRepayRateMap,
          }
          formatTrendData = this.formatMapData(_repayTrendData, 'time', 'repayRate');
          for (let [key, val] of Object.entries(_repayTrendData)) {
            if (val) {
              _xFields.push(key);
            }
          }
        }
        break;
      case 'overdue':
          formatTrendData = overdueTrendData ? this.formatMapData(overdueTrendData, 'time', '') : [];
          if (overdueTrendData) {
            for (let [key, val] of Object.entries(overdueTrendData)) {
              if (val) {
                _xFields.push(key);
              }
            }
          }
        break;
      default:
        break;
    }

    const ds = new DataSet();
    const dv = ds.createView().source(formatTrendData);
    dv.transform({
      type: "fold",
      fields: _xFields,
      // 展开字段集
      key: "range",
      // key字段
      value: "_rate" // value字段
    });
    const cols = {
      time: {
        range: [0, 1]
      }
    };

    const topTips_A = "正常还款+逾期还款+展期虚拟还款";
    const topTips_B = "还款日为昨日用户的展期订单总额"
    const topTips_C = "还款日为当日用户的展期订单总额"

    return (
      <div >
        <Card
          loading ={loading}
          style={{background:'#f0f2f5'}}
        >
          {
            type =='back' && abData && nbData && obData ?
              <Row gutter={24}>
                <Col {...topColResponsiveProps}>
                  <ChartCard
                    bordered={true}
                    title='今日回款（总）'
                    loading={loading}
                    total={'￥'+ abData.todayRepayAmount}
                    footer={
                      <div>
                        <div style={{float: 'left', marginRight: 16 }}>
                          <span>应还本金</span>
                          <span style={{'display': 'inlineBlock', marginLeft: 8, color: 'rgba(0,0,0,.85)' }}>{ '￥' + abData.loanEndItemAmount }</span>
                        </div>
                        <div style={{float: 'left'}}>
                          <span>应还本息</span>
                          <span style={{'display': 'inlineBlock', marginLeft: 8, color: 'rgba(0,0,0,.85)' }}>{ '￥' + abData.loanEndTotalAmount }</span>
                        </div>
                      </div>
                    }
                    contentHeight={46}
                  >
                    <AntTooltip title={abData.repayRate}><div style={{zIndex: 1000, position: 'absolute', width: '100%', height: 18}}></div></AntTooltip>
                    <MiniProgress percent={parseInt(abData.repayRate.replace('%', ''))} strokeWidth={8} target={80} />
                  </ChartCard>
                </Col>
                <Col {...topColResponsiveProps}>
                  <ChartCard
                    bordered={true}
                    title='今日回款（新）'
                    loading={loading}
                    total={'￥'+nbData.todayRepayAmount}
                    footer={
                      <div>
                        <div style={{float: 'left', marginRight: 16 }}>
                          <span>应还本金</span>
                          <span style={{'display': 'inlineBlock', marginLeft: 8, color: 'rgba(0,0,0,.85)' }}>{ '￥' + allData.nbData.loanEndItemAmount }</span>
                        </div>
                        <div style={{float: 'left'}}>
                          <span>应还本息</span>
                          <span style={{'display': 'inlineBlock', marginLeft: 8, color: 'rgba(0,0,0,.85)' }}>{ '￥' + allData.nbData.loanEndTotalAmount }</span>
                        </div>
                      </div>
                    }
                    contentHeight={46}
                  >
                    <AntTooltip title={nbData.repayRate}><div style={{zIndex: 1000, position: 'absolute', width: '100%', height: 18}}></div></AntTooltip>
                    <MiniProgress percent={parseInt(nbData.repayRate.replace('%', ''))} strokeWidth={8} target={80} />
                  </ChartCard>
                </Col>
                <Col {...topColResponsiveProps}>
                  <ChartCard
                    bordered={true}
                    title='今日回款（老）'
                    loading={loading}
                    total={'￥'+obData.todayRepayAmount}
                    footer={
                      <div>
                        <div style={{float: 'left', marginRight: 16 }}>
                          <span>应还本金</span>
                          <span style={{'display': 'inlineBlock', marginLeft: 8, color: 'rgba(0,0,0,.85)' }}>{ '￥' + obData.loanEndItemAmount }</span>
                        </div>
                        <div style={{float: 'left'}}>
                          <span>应还本息</span>
                          <span style={{'display': 'inlineBlock', marginLeft: 8, color: 'rgba(0,0,0,.85)' }}>{ '￥' + obData.loanEndTotalAmount }</span>
                        </div>
                      </div>
                    }
                    contentHeight={46}
                  >
                    <AntTooltip title={obData.repayRate}><div style={{zIndex: 1000, position: 'absolute', width: '100%', height: 18}}></div></AntTooltip>
                    <MiniProgress percent={parseInt(obData.repayRate.replace('%', ''))} strokeWidth={8} target={80} />
                  </ChartCard>
                </Col>
              </Row>
              :
              type == 'overdue' && aoData && noData && ooData ?
                <Row gutter={24}>
                  <Col {...topColResponsiveProps}>
                    <ChartCard
                      bordered={true}
                      title='今日逾期回款（总）'
                      loading={loading}
                      total={'￥'+aoData.todayOverdueRepayAmount}
                      footer={
                        <div>
                          <div style={{float: 'left', marginRight: 16 }}>
                            <span>应还本金</span>
                            <span style={{'display': 'inlineBlock', marginLeft: 8, color: 'rgba(0,0,0,.85)' }}>{ '￥' + aoData.overdueItemAmount }</span>
                          </div>
                          <div style={{float: 'left'}}>
                            <span>应还本息</span>
                            <span style={{'display': 'inlineBlock', marginLeft: 8, color: 'rgba(0,0,0,.85)' }}>{ '￥' + aoData.overdueItemAmount }</span>
                          </div>
                        </div>
                      }
                      contentHeight={46}
                    >
                    </ChartCard>
                  </Col>
                  <Col {...topColResponsiveProps}>
                    <ChartCard
                      bordered={true}
                      title='今日逾期回款（新）'
                      loading={loading}
                      total={'￥'+noData.todayOverdueRepayAmount}
                      footer={
                        <div>
                          <div style={{float: 'left', marginRight: 16 }}>
                            <span>应还本金</span>
                            <span style={{'display': 'inlineBlock', marginLeft: 8, color: 'rgba(0,0,0,.85)' }}>{ '￥' + noData.overdueItemAmount }</span>
                          </div>
                          <div style={{float: 'left'}}>
                            <span>应还本息</span>
                            <span style={{'display': 'inlineBlock', marginLeft: 8, color: 'rgba(0,0,0,.85)' }}>{ '￥' + noData.overdueTotalAmount }</span>
                          </div>
                        </div>
                      }
                      contentHeight={46}
                    >
                    </ChartCard>
                  </Col>
                  <Col {...topColResponsiveProps}>
                    <ChartCard
                      bordered={true}
                      title='今日逾期回款（老）'
                      loading={loading}
                      total={'￥'+ooData.todayOverdueRepayAmount}
                      footer={
                        <div>
                          <div style={{float: 'left', marginRight: 16 }}>
                            <span>应还本金</span>
                            <span style={{'display': 'inlineBlock', marginLeft: 8, color: 'rgba(0,0,0,.85)' }}>{ '￥' + ooData.overdueItemAmount }</span>
                          </div>
                          <div style={{float: 'left'}}>
                            <span>应还本息</span>
                            <span style={{'display': 'inlineBlock', marginLeft: 8, color: 'rgba(0,0,0,.85)' }}>{ '￥' + ooData.overdueTotalAmount }</span>
                          </div>
                        </div>
                      }
                      contentHeight={46}
                    >
                    </ChartCard>
                  </Col>
                </Row>
                :
                totalRepayCountData ? 
                <Row gutter={24}>
                  <Col {...topColResponsiveProps_B}>
                    <ChartCard
                      bordered={true}
                      title={'昨日总回款'}
                      loading={loading}
                      action={<AntTooltip trigger="click" title={topTips_A}><Icon type="question-circle" /></AntTooltip>}
                      total={ '￥' + totalRepayCountData.yesterday.totalRepayAmount }
                      footer={
                        <div>
                          <div style={{float: 'left', marginRight: 16 }}>
                            <span>正常还款</span>
                            <span style={{'display': 'inlineBlock', marginLeft: 8, color: 'rgba(0,0,0,.85)' }}>{ '￥' + totalRepayCountData.yesterday.normalRepayAmount }</span>
                          </div>
                          <div style={{float: 'left'}}>
                            <span style={{'display': 'inlineBlock' }}>逾期还款</span>
                            <span style={{'display': 'inlineBlock', marginLeft: 8, color: 'rgba(0,0,0,.85)' }}>{ '￥' + totalRepayCountData.yesterday.overdueRepayAmount }</span>
                          </div>
                          <div style={{float: 'right'}}>
                            <span>展期回款</span>
                            <AntTooltip trigger="click" title={topTips_B}><Icon type="question-circle" style={{cursor: 'pointer'}} /></AntTooltip>
                           <span style={{'display': 'inlineBlock', marginLeft: 8, color: 'rgba(0,0,0,.85)' }}>{ '￥' + totalRepayCountData.yesterday.extendRepayAmount}</span>
                          </div>
                        </div>
                      }
                      contentHeight={46}
                    >
                    </ChartCard>
                  </Col>
                  <Col {...topColResponsiveProps_B}>
                    <ChartCard
                      bordered={true}
                      title={'今日总回款'}
                      loading={loading}
                      action={<AntTooltip trigger="click" title={topTips_A}><Icon type="question-circle" /></AntTooltip>}
                      total={ '￥' + totalRepayCountData.today.totalRepayAmount }
                      footer={
                        <div>
                          <div style={{float: 'left', marginRight: 16 }}>
                            <span>正常还款</span>
                            <span style={{'display': 'inlineBlock', marginLeft: 8, color: 'rgba(0,0,0,.85)' }}>{ '￥' + totalRepayCountData.today.normalRepayAmount }</span>
                          </div>
                          <div style={{float: 'left'}}>
                            <span style={{'display': 'inlineBlock' }}>逾期还款</span>
                            <span style={{'display': 'inlineBlock', marginLeft: 8, color: 'rgba(0,0,0,.85)' }}>{ '￥' + totalRepayCountData.today.overdueRepayAmount }</span>
                          </div>
                          <div style={{float: 'right'}}>
                            <span>展期回款</span>
                            <AntTooltip trigger="click" title={topTips_C}><Icon type="question-circle" style={{cursor: 'pointer'}} /></AntTooltip>
                           <span style={{'display': 'inlineBlock', marginLeft: 8, color: 'rgba(0,0,0,.85)' }}>{ '￥' + totalRepayCountData.today.extendRepayAmount}</span>
                          </div>
                        </div>
                      }
                      contentHeight={46}
                    >
                    </ChartCard>
                  </Col>
                </Row> 
                : ''
          }
        </Card>

        <Card style={{marginTop:30}}>
          <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
            <Col md={8} sm={8}>
            { 
              type == 'overdue' ?
              <Select style={{width:120,float:'left'}} defaultValue={currentUser? currentUser : userType[0].val} onChange={userSelectFn}>
                {
                  userType.map((item,i)=>{
                    return <Option value={item.val} key={i}>{item.tit}</Option>
                  })
                }
              </Select>
              : ''
            }
            </Col>
            <Col md={4} sm={16}>

            </Col>
            <Col md={12} sm={24}>
              <RangePicker
                onChange={datePickerFn} 
                defaultValue={_dateRanges}
                ranges={{
                  近7天: [moment().subtract(7, 'days'), moment()],
                  近14天: [moment().subtract(14, 'days'), moment()],
                  近30天: [moment().subtract(30, 'days'), moment()],
                }}
              />
            </Col>
          </Row>

          {
            type == 'all' || type == 'back' ? 
            <div>
              <Chart height={400} data={dv} scale={cols} forceFit onTooltipChange={(ev)=>{
                let items = ev.items; // tooltip显示的项
                let itemBuf = [];
                itemBuf.push(...items); //非引用拷贝
                items.splice(0); // 清空数组
                itemBuf.forEach((origin, index, arr) => {
                  items.push({
                    name: origin.name,
                    marker: true,
                    title: origin.title,
                    color: origin.color,
                    value: this.selectDataByAmount(origin.name, origin.title, '还款金额')
                  });
                  items.push({
                    name: origin.name.replace('还款金额', '还款笔数'),
                    marker: true,
                    title: origin.title,
                    color: origin.color,
                    value: this.selectDataByAmount(origin.name, origin.title, '还款笔数')
                  });
                  items.push({
                    name: origin.name.replace('还款金额', '还款率'),
                    title: origin.title,
                    marker: true,
                    color: origin.color,
                    value: this.selectDataByAmount(origin.name, origin.title, '还款率')
                  });
                });
              }}>
                <Legend />
                <Axis name="time" />
                <Axis name="_rate" label={{ formatter: val => `${val}%` }} />
                <Tooltip crosshairs={{ type: "y" }} itemTpl="<tr><td style=&quot;width:70px&quot;>{name}:</td><td>{value}</td></tr>" />
                <Geom type="line" position="time*_rate" size={2} color={"range"} />
                <Geom type="point" position="time*_rate" size={4} shape={"circle"} color={"range"} style={{ stroke: "#fff", lineWidth: 1 }} />
              </Chart>
            </div> 
            : 
            <div>
              <Chart height={400} data={dv} scale={cols} forceFit>
                <Legend />
                <Axis name="time" />
                <Axis name="_rate" label={{ formatter: val => `${val}` }} />
                <Tooltip crosshairs={{ type: "y" }} />
                <Geom type="line" position="time*_rate" size={2} color={"range"} />
                <Geom type="point" position="time*_rate" size={4} shape={"circle"} color={"range"} style={{ stroke: "#fff", lineWidth: 1 }} />
              </Chart>
            </div> 
          }

        </Card>
        <Card style={{marginTop:30}}>
        <GeneralTableComponent
            loading={loading}
            data={ type == 'all' ? totalRepayTableData : ( type=='back' ? repayTableData: overdueTableData ) }
            // data={type=='back' ? repayTableData: overdueTableData}
            columns={ type == 'all' ? columnsAll : ( type=='back' ? columns1: columns2 ) }
            onChange={tableChange}
            rowKey={'date'}
          />
        </Card>
      </div>
    );
  }
}
